﻿using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace KLTP2UI
{
	public partial class FilterEditor : Form
	{
		public FilterEditor(Filter filter)
		{
			InitializeComponent();
			groupBox1.Controls
				.Cast<CheckBox>()
				.Where(control => filter.Types.Contains(control.Text))
					.ToList()
					.ForEach(c => c.Checked = true);
			lbSelected.Items.AddRange(filter.Services.ToArray());
			for (uint i = 0; i < DllMem.FilterGetServicesCount(); i++)
			{
				var srv = Marshal.PtrToStringAnsi(DllMem.FilterGetServiceById(i)) ?? "";
				if (!lbSelected.Items.Contains(srv))
					lbAvailable.Items.Add(srv);
			}
			Result = new Filter();
		}

		public Filter Result { get; private set; }

		private void BtnOkClick(object sender, EventArgs e)
		{
			Result.MakeDefault();
			groupBox1.Controls
				.Cast<CheckBox>()
				.Where(control => control.Checked)
					.ToList()
					.ForEach(c => Result.Types.Add(c.Text));
			Result.Services.AddRange(lbSelected.Items.Cast<String>());
			DialogResult = DialogResult.OK;
			Close();
		}

		private void BtnSelectAllClick(object sender, EventArgs e)
		{
			lbSelected.Items.AddRange(lbAvailable.Items);
			lbAvailable.Items.Clear();
		}

		private void BtnDeselectAllClick(object sender, EventArgs e)
		{
			lbAvailable.Items.AddRange(lbSelected.Items);
			lbSelected.Items.Clear();
		}

		private void BtnSelectOneClick(object sender, EventArgs e)
		{
			var idx = lbAvailable.SelectedIndex;
			lbSelected.Items.Add(lbAvailable.SelectedItem);
			lbAvailable.Items.Remove(lbAvailable.SelectedItem);
			if (lbAvailable.Items.Count > 0)
				lbAvailable.SelectedIndex = Math.Min(lbAvailable.Items.Count - 1, idx);
		}

		private void BtnDeselectOneClick(object sender, EventArgs e)
		{
			var idx = lbSelected.SelectedIndex;
			lbAvailable.Items.Add(lbSelected.SelectedItem);
			lbSelected.Items.Remove(lbSelected.SelectedItem);
			if (lbSelected.Items.Count > 0)
				lbSelected.SelectedIndex = Math.Min(lbSelected.Items.Count - 1, idx);

		}

		private void LbAvailableSelectedIndexChanged(object sender, EventArgs e)
		{
			btnSelectOne.Enabled = lbAvailable.SelectedIndex > -1;
		}

		private void LbSelectedSelectedIndexChanged(object sender, EventArgs e)
		{
			btnDeselectOne.Enabled = lbSelected.SelectedIndex > -1;
		}

		private void LbAvailableDoubleClick(object sender, EventArgs e)
		{
			BtnSelectOneClick(sender, e);
		}

		private void LbSelectedDoubleClick(object sender, EventArgs e)
		{
			BtnDeselectOneClick(sender, e);
		}

		private void BtnSortClick(object sender, EventArgs e)
		{
			lbAvailable.Sorted = true;
			lbAvailable.Sorted = false;
			lbSelected.Sorted = true;
			lbSelected.Sorted = false;
		}
	}
}
